package com.qfedu.dao.impl;

import com.qfedu.dao.UserDao;
import com.qfedu.model.User;
import com.qfedu.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.SQLException;
import java.util.List;

/**
 * Title: UserDaoImpl
 *
 * @author Wenn.
 * @Package com.qfedu.dao.impl
 * @Date 2023/4/18 19:31
 * @Note
 */
public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());

    @Override
    public int regist(User user) {
        //定义sql
        String sql = "insert into t_user values(null,?,?,?)";
        int update = jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getEmail());
        return update;
    }

    @Override
    public User findUser(String username) {
        String sql = "select * from t_user where username=?";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), username);
        if (users!=null&&users.size()==1){
            return users.get(0);
        }
        return null;
}


    @Override
    public User login(User user) {
        //定义sql
        String sql = "select * from t_user where username=? and password=?";
        List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), user.getUsername(), user.getPassword());
        if (query != null && query.size() == 1) {
            return query.get(0);
        }
        return null;
    }

    @Override
    public int updateUser(User user) {
        String sql = "update t_user set username=?,password=?,email=? where id=?";
        int update = jdbcTemplate.update(sql, user.getUsername(),user.getPassword(),user.getEmail(), user.getId());
        return update;
    }

    @Override
    public User findUserById(int id) {
        String sql = "select * from t_user where id =?";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), id);
        if (users!=null&&users.size()==1){
            return users.get(0);
        }
        return null;
    }

}